package com.ruoyi.keypair.service.impl;

import com.ruoyi.keypair.domain.DidUserKeypair;
import com.ruoyi.keypair.mapper.DidUserKeypairMapper;
import com.ruoyi.keypair.service.IDidUserKeypairService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Service
public class DidUserKeypairServiceImpl implements IDidUserKeypairService {

    @Resource
    private DidUserKeypairMapper keypairMapper;

    @Override
    public Map<String, String> generateKeyPair(Long userId) {
        try {
            // 生成 RSA 密钥对
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            KeyPair keyPair = keyGen.generateKeyPair();

            String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
            String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());

            // 保存公钥到数据库
            DidUserKeypair kp = new DidUserKeypair();
            kp.setUserId(userId);
            kp.setPublicKey(publicKey);
            keypairMapper.insertDidUserKeypair(kp);

            // 返回公钥和私钥给用户
            Map<String, String> result = new HashMap<>();
            result.put("publicKey", publicKey);
            result.put("privateKey", privateKey);
            return result;

        } catch (Exception e) {
            throw new RuntimeException("生成密钥对失败", e);
        }
    }

}
